package my.jwds.p16;

import java.util.Arrays;
import java.util.TreeSet;

public class ThreeSumClosest {

    public static void main(String[] args) {

        Solution obj = new Solution();
        long start = System.currentTimeMillis();
        System.out.println("运行时间:" + (System.currentTimeMillis() - start));
        TreeSet set = new TreeSet();
    }

    static class Solution {


        public int threeSumClosest(int[] nums, int target) {
            Arrays.sort(nums);
            int res = 0,minDiff = 10000000;
            int prev = Integer.MAX_VALUE;
            for (int i = 0; i < nums.length-2; i++) {
                int num1 = nums[i];
                if (num1 == prev) continue;
                prev = num1;

                int num2Prev = Integer.MAX_VALUE;
                int num3Index = nums.length -1;
                for (int j = i+1; j < num3Index; j++) {
                    int num2 = nums[j];
                    if (num2 == num2Prev)continue;
                    num2Prev = num2;


                    int sum = 0;
                    while(num3Index!=j){
                        sum = num1+num2+nums[num3Index--];
                        if (Math.abs(sum -target) < minDiff){
                            minDiff = Math.abs(sum -target);
                            res = sum;
                        }
                        if (sum < target) break;
                        if (sum == target)return target;
                    }
                    if (sum < target){
                        num3Index ++;
                        continue;
                    }

                }


            }
            return res;
        }


    }
}